import React, {Component} from 'react'
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  Platform,
  TouchableOpacity,
  ActivityIndicator,
  ScrollView,
  Image,
  ImageBackground,
  FlatList,
  WebView,
  BackHandler
} from 'react-native'
import {Actions} from "react-native-router-flux";
import ICON from 'react-native-vector-icons/Ionicons'
import * as stringUtils from './../../utils/srting'
import Toast2, {
  DURATION
} from 'react-native-easy-toast'
import {Toast, Overlay, SegmentedBar, Carousel} from 'teaset'
import * as ShareMenu from './../common/ShareMenu'
import AutoHeightWebView from 'react-native-autoheight-webview';

// 引入sdk
import RNAlibcSdk, {AlibcTradeWebView} from 'react-native-alibc-sdk';
import { SafeAreaView } from 'react-navigation';
import { getUserId } from "../../services/token";

const {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get("window");

const PARAMS = {
  pid: "mm_108042659_0_0",
  forceH5: false
};

class TaobaoWebScene extends Component{
  constructor(props){
    super(props)

    this.state = {
      webLoading: true,
      like: false,
      goodsSelect: 0,
      isScroll: false,
      imglist: [],
      contentHtml: '',
      quanUrl: ''
    }


  }

  componentDidMount() {
    /* 初始化sdk(此方法为异步， 确保回调执行后再进行下一步操作)
     * 参数
     * pid: 绑定阿里妈妈帐号后在百川后台查询此帐号
     * forceH5：强制浏览器打开页面
     * callback: 回调函数
     */

    // RNAlibcSdk.init(PARAMS.pid, PARAMS.forceH5, (err) => {
    //   if (!err)
    //     console.log("init taobao success")
    //   else
    //     console.log(err)
    // });

    this.props.actions.userInfo()
    this.startTime = Date.parse(new Date()) / 1000
    this.props.actions.getGoodsContent(this.props.auctionId)
    this.props.actions.getUserLike(this.props.auctionId)
  }


  componentWillReceiveProps(nextProps) {
    const {goodsContent, userLike, postCollect, refresh, userInfo, saveRelation} = nextProps


    RNAlibcSdk.init(PARAMS.pid, PARAMS.forceH5, (err) => {
      if (!err)
        console.log("init taobao success")
      else
        console.log(err)
    });


    // if(nextProps.refresh && userInfo.isLoading === false){
    //   console.log(this.props)
    //
    //
    //   this.props.actions.userInfo()
    //   this.props.actions.getGoodsContent(this.props.auctionId)
    //   this.props.actions.getUserLike(this.props.auctionId)
    // }


    if(this.props.userInfo !== userInfo){
      this.setState({isRefreshing: false});
      if (userInfo.error !== false) {
        Actions.login()


    }else{


        if(userInfo && userInfo.data && !userInfo.data.relation_id) {
          // Actions.webView({
          //   url: 'https://oauth.taobao.com/authorize?response_type=code&client_id=24622074&view=wap&redirect_uri=https://tao.vyxjj.com/alicallback?userid=' + userInfo.data.id,
          //   title: '授权登陆'
          // })

          RNAlibcSdk.login((err, taoBaouserInfo) => {
            if (!err){
                Actions.taoBaoWebView({
                  userId: userInfo.data.id,
                  title: '授权登陆'
                })
              }
              else
                console.log(err)
            })
          // Actions.webView({url:'https://oauth.taobao.com/authorize?response_type=code&client_id=24622074&view=wap&redirect_uri=https://tao.vyxjj.com/alicallback?userid='+this.props.userInfo.data.id, title:'授权登陆'})

          //
        }
        // console.log(userInfo)
      }

    }



    if(refresh === true && goodsContent.isLoading === false){
      Actions.refresh({
        refresh: false
      });
      this.setState({goodsSelect: 0})
      this.props.actions.getGoodsContent(nextProps.auctionId)
      this.props.actions.getUserLike(nextProps.auctionId)
    }


    if(this.props.goodsContent !== goodsContent){

      if (goodsContent.error !== false) {
        if (goodsContent.error.status === 401) {
          Actions.login()
          return;
        }

        this.toast.show(goodsContent.error.message)
        Actions.pop()
      }else{
        if (goodsContent.isLoading) {

        }else{
          if (goodsContent.data) {
            goodsContent.data.imglist.unshift(goodsContent.data.imgtop)
            this.setState({imglist:goodsContent.data.imglist})
            this.getGoodsContentImg(goodsContent.data.auctionId);
          }
        }
      }

    }


    if(this.props.userLike !== userLike){
      if (userLike.error !== false) {
        if (userLike.error.status === 401) {
          this.setState({like: false})
        }

      }else{
        if (userLike.isLoading) {

        }else{
          this.setState({like: true})
        }
      }
    }


    if(this.props.postCollect !== postCollect){
      if (postCollect.error !== false) {
        if (postCollect.error.status === 401) {
          Actions.login()
          return;
        }

        this.toast.show(postCollect.error.message)

      }else{
        if (postCollect.isLoading) {

        }else{
          Toast.success(postCollect.data)
          this.setState({like: true})
        }
      }
    }

  }



  //浏览记录
  componentWillUnmount() {
    this.uploadHistory()//上传浏览记录
  }


  //获取淘宝详情
  getGoodsContentImg(id){
    let url = 'https://api.m.taobao.com/h5/mtop.taobao.detail.getdesc/6.0/?api=mtop.taobao.detail.getdesc&data={"id":"'+id+'","type":"1"}';
    fetch(url,{
      method: 'GET',
    }).then(function (res) {
      return res.json()
    }).then(function (result) {
      if(result && result.data.pcDescContent){
        let imgReg = /<img.*?(?:>|\/>)/gi
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
        let str = result.data.pcDescContent
        let arr = str.match(imgReg)  //筛选出所有的img
        let html = '';
        if(arr && arr.length > 0){
          for (let i = 0; i < arr.length; i++) {
            let src = arr[i].match(srcReg)
            // 获取图片地址
            if(src && src[1].indexOf(".gif") === -1){
              html+= '<Img src="https:'+src[1]+'" />'
            }

          }
        }
        this.setState({
          contentHtml:html,
        },)

      }
    }.bind(this)).done()
  }


  //上传浏览记录
  uploadHistory(){
    let startTime = this.startTime
    let endTime = Date.parse(new Date()) / 1000
    this.props.actions.postUserHistory({...this.props.goodsContent.data, startTime, endTime,  resultJifen:1})
  }


  //点击相关产品
  clickGuanlian(e){
    let resultJifen = 1;
    let startTime = this.startTime
    let endTime = Date.parse(new Date()) / 1000
    this.props.actions.postUserHistory({resultJifen, ...e, startTime, endTime,})
    Actions.refresh({resultJifen, ...e, refresh: true})
  }


  _show(param) {
    // let param = {type: "url", payload: this.state.quanUrl}
    RNAlibcSdk.show(param, (err, info) => {
      if (!err)
        console.log(info)
      else
        console.log(err)
    });
    // Actions.webView({url:'https://oauth.taobao.com/authorize?response_type=code&client_id=24622074&view=wap&redirect_uri=https://tao.vyxjj.com/alicallback?userid='+this.props.userInfo.data.id, title:'授权登陆'})
    // let params = {
    //   payload: 'https://oauth.taobao.com/authorize?response_type=code&client_id=24622074&view=wap&redirect_uri=https://tao.vyxjj.com/alicallback',
    //   type: "url",
    // }
    //

    // RNAlibcSdk.login((err, userInfo) => {
    //   if (!err){
    //     }
    //
    //     else
    //       console.log(err)
    //   })
    // );

  }



  //产品信息选项卡样式
  renderGoodSelectContent(){
    return(
      <SegmentedBar
        style={{marginTop:10, height:40, borderBottomWidth:1, borderBottomColor:'#e8e8e8'}}
        indicatorType='boxWidth'
        indicatorLineColor='#E12F32'
        onChange={(props)=>{
          // this.myScrollView.scrollTo({x: 0, y: deviceHeight * 0.92, animated: true});
          this.setState({goodsSelect: props})
        }}
      >
        <SegmentedBar.Item
          title='商品详情'
          titleStyle={{color:'#5f5f5f', fontSize:14}}
          activeTitleStyle={{color:'#E12F32', fontSize:14}}
        />
        {/*<SegmentedBar.Item*/}
          {/*title='买家评论'*/}
          {/*titleStyle={{color:'#5f5f5f', fontSize:15}}*/}
          {/*activeTitleStyle={{color:'#E12F32', fontSize:15}}*/}
        {/*/>*/}
        <SegmentedBar.Item
          title='相关推荐'
          titleStyle={{color:'#5f5f5f', fontSize:14}}
          activeTitleStyle={{color:'#E12F32', fontSize:14}}
        />
      </SegmentedBar>
    )
  }


  //产品信息样式
  renderGoodContent(data){
    if(this.state.goodsSelect === 0){
      if(this.state.contentHtml){
        // console.log(this.state.contentHtml)
        return (
          <View style={{flex:1, backgroundColor:'#fff'}}>
            <View style={{flex:1, backgroundColor:'#fff', alignItems:'center', flexWrap:'wrap',
              flexDirection:'row', padding:5, marginBottom:10}}>
              {data.goods_info.rate && data.goods_info.rate.keywords && data.goods_info.rate.keywords.length > 0 ?
                data.goods_info.rate.keywords.map(function (e, i) {
                  if(e.type == 1){
                    return(
                      <View style={styles.impressionGood} key={i}>
                        <Text style={{color:'#666', fontSize:13}}>{e.word}({e.count})</Text>
                      </View>
                    )
                  }else{
                    return(
                      <View style={styles.impressionBad} key={i}>
                        <Text style={{color:'#fff',  fontSize:13}}>{e.word}({e.count})</Text>
                      </View>
                    )
                  }

                })
              :null
              }
            </View>
            <AutoHeightWebView
              source={{html: this.state.contentHtml}}
              style={{width:deviceWidth, backgroundColor:'#fff'}}
              customStyle={'img{width:'+deviceWidth+'} .desc_anchor{height: 0px} div{height:auto !important; width:'+deviceWidth+' !important} '}
            />
          </View>
        )
      }
    }else if(this.state.goodsSelect === 2){
      //console.log(data.plist)
      return(
        <View style={{flex:1}}>
          {data.plist.map(function (e, i) {
            return(
              <View style={{flex:1, padding: 10, backgroundColor:'#fff', marginBottom:5}} key={i}>
                <View style={{flex:1, justifyContent:'space-between', alignItems:'center', flexDirection:'row', marginBottom:10}}>
                  <View style={{flexDirection:'row', alignItems:'center'}}>
                    <Image source={{uri:'https://tao.vyxjj.com/build/images/tx.jpg'}} style={{width:30, height:30, marginRight:5}}/>
                    <Text style={{fontSize:16}}>{e.displayUserNick}</Text>
                  </View>
                  <Text style={{color:'#9c9c9c', fontSize:16}}>{e.rateDate}</Text>
                </View>
                <Text style={{fontSize:16, marginBottom:10}}>{e.rateContent}</Text>
                <View style={{flexDirection:'row', flexWrap: 'wrap'}}>
                  {e.pics.map(function (e, i) {
                    let pirUrl = 'http:'+e
                    return(
                      <Image source={{uri:pirUrl}} style={{width:95, height:150, resizeMode: "contain", marginRight:3, marginBottom:5}} key={i}/>
                    )
                  })}
                </View>
              </View>
            )
          })}
        </View>
      )
    }else if(this.state.goodsSelect === 1){

      if(data.guanlian.length > 0){
        return(
          <View style={{flex:1, backgroundColor:'#fff', flexDirection:'row', flexWrap: 'wrap'}}>
            {data.guanlian.map(function (e, i) {
              let price = e.zkPrice - e.couponAmount;
              let quan;
              if(e.couponAmount == 0){
                quan = '折扣价'
              }else{
                quan = e.couponAmount +'元券'
              }

              return(
                <TouchableOpacity  style={{width:'48%', margin: 2, backgroundColor:'#fff', padding: 5, borderWidth: 1, borderColor: '#eee'}}
                                  onPress={()=>{this.clickGuanlian(e)}}
                                  key={i}>
                  <Image source={{uri: e.pictUrl}} style={{height:180}} resizeMode='contain'/>
                  <Text numberOfLines={2} ellipsizeMode='tail' style={styles.itemTitle}>
                    <Text textAlign='justify' style={styles.postage} textAlignVertical='center'> 包邮 </Text> {e.title}
                  </Text>
                  <View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
                    <Text style={{color:'#acacac', fontSize:13}}>原价 ¥ {e.zkPrice}</Text>
                    <Text style={{color:'#acacac', fontSize:13}}>月销 {e.biz30day}</Text>
                  </View>
                  <View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginBottom:5}}>
                    <Text style={{color:'#EF422D', fontSize:13}}>¥ <Text style={{fontSize:25, fontWeight: 'bold'}}>{price.toFixed(2)}</Text></Text>
                    <ImageBackground style={{width:60, height:40, justifyContent:'center', alignItems:'center'}} resizeMode='contain' source={require('./../../../assets/images/quan.png')}>
                      <Text style={{color:'#fff', fontSize:13}}>{quan}</Text>
                    </ImageBackground>
                  </View>
                </TouchableOpacity>
              )
            }.bind(this))}
          </View>
        )

      }else{
        return(
          <View style={{height:50, justifyContent:'center', alignItems:'center', backgroundColor:'#fff'}}>
            <Text>没有相关推荐</Text>
          </View>
        )
      }

    }

  }


  //产品详情
  renderContent(){
    const {
      isLoading,
      data,
      error
    } = this.props.goodsContent
    // console.log(data);

    if(data && !isLoading){
      let price = data.zk_final_price - data.quan
      let quan;
      if(data.couponAmount == 0){
        quan = '折扣价+'+data.jifen+'元        '
      }else{
        quan = data.couponAmount +'元优惠券 \n预计收入：'+data.jifen+'元'
      }
      return(
        <ScrollView style={{flex:1, backgroundColor:'#F5F5F5'}}
                    ref={(view) => { this.myScrollView = view; }}
                    showsVerticalScrollIndicator={false}
                    onScroll={(e)=>{
                      let offsetY = e.nativeEvent.contentOffset.y;
                      if(offsetY > 400){
                        this.setState({isScroll: true})
                      }else{
                        this.setState({isScroll: false})
                      }
                    }}
        >
          <Carousel style={{height: 380}} control={true}>
            {this.state.imglist.map(function (e, i) {
                    return(
                      <Image source={{uri:e}} style={{flex:1, height:380}} key={i}  resizeMode='stretch' defaultSource={require('./../../../assets/images/defaultImg.jpg')}/>
                    )
            })}
          </Carousel>
          <View style={styles.titleContainer}>
            <View style={{ flexDirection: 'row', paddingRight: 5}}>
              {data.user_type == 1  ?
                <Image source={require('./../../../assets/images/tmall.png')} style={{width: 18, height: 18, marginRight: 5}}/>
                :  <Image source={require('./../../../assets/images/taobao.png')} style={{width: 18, height: 18, marginRight: 5}}/>
              }
              <Text style={{fontSize: 15, marginRight:18}} numberOfLines={2} >{data.title}</Text>
            </View>
            <Text style={{color: "#999", fontSize:14, lineHeight:40}}>原价:￥{data.zk_final_price}</Text>
            <View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center'}}>
              <View style={{flexDirection:'row', justifyContent:'center', alignItems:'center', height:40}}>
                <Image style={{height:60, width:50, resizeMode: "contain"}} source={{uri: 'https://tao.vyxjj.com/build/images/quanhou.png'}}/>
                <Text style={{fontSize:20, color:"#f00", marginLeft: 3}}>￥{price.toFixed(2)}</Text>
              </View>
              <Text style={{color: "#999", fontSize:14}}>包邮 月销{data.volume}</Text>
            </View>
            {data.pingfen.length > 1 ?
              <View style={{height:50, marginBottom: 10, justifyContent:'space-between', alignItems:'center', flexDirection:'row'}}>
                {data.pingfen.map(function (e, i) {
                  if(i){
                    return(
                      <Text key={i} style={{fontSize:15}}>{e.title}：<Text style={{color:'#e13e4c', fontWeight: "bold"}}>{e.score}</Text></Text>
                    )
                  }else{
                    return null;
                  }

                })}
              </View>
              : null
            }


            <ImageBackground source={{uri:'https://tao.vyxjj.com/build/images/quan1.jpg'}} style={{width: deviceWidth - 20, height: deviceHeight / 9, flexDirection:'row', alignItems:'center', marginBottom:8, justifyContent:'center'}} resizeMode='stretch'>


              <Text style={{color:'#fff', fontSize:14, flex:6.5, marginLeft:30, lineHeight:25}}>{quan}</Text>

              <TouchableOpacity style={{height:35, justifyContent:'flex-end', alignItems:'center', flex:3.5}}
                                activeOpacity={1}
                                onPress={()=>{
                                  let datas = {
                                    content:data.title,
                                    jifen: data.jifen,
                                    quan: data.quan,
                                    kouling: data.kouling,
                                    imglist: data.imglist,
                                    zkPrice: data.zkPrice,
                                    pictUrl: data.pictUrl,
                                  }
                                  Actions.shareModel(datas)
                                }}
              >
                <Text style={{color:'#fff', fontSize:14}}>分享</Text>
              </TouchableOpacity>

              <TouchableOpacity style={{height:35, justifyContent:'flex-end', alignItems:'center', flex:3.5}}
                                activeOpacity={1}
                                onPress={()=>{
                                  // console.log(data.coupon_share_url)
                                  this.uploadHistory()
                                  this._show({type: "url", payload:'https:'+data.coupon_share_url});
                                }}
              >
                <Text style={{color:'#fff', fontSize:14, marginRight:20}}>领券</Text>
              </TouchableOpacity>
            </ImageBackground>
            <View style={{flex:1, height:0, borderWidth: 1, borderStyle:'dashed', borderRadius:0.1, borderColor:'#f54d23', marginBottom:10}}></View>
          </View>

          {this.renderGoodSelectContent()}
          {this.renderGoodContent(data)}
        </ScrollView>
      )
    }
  }


  renderShare(data){
    let shareUrl;
    if(getUserId()){
      shareUrl = 'https://tao.vyxjj.com/#/goods?id='+data.auctionId+'&shareid='+getUserId()
    }else{
      shareUrl = 'https://tao.vyxjj.com/#/goods?id='+data.auctionId
    }

    return(
      <TouchableOpacity
        onPress={()=>{
          // Overlay.show(ShareMenu.ShareMenu({
          //   'cate': 'good',
          //   'title': stringUtils.delHtmlTag(data.title),
          //   'description': '领优惠券+返利+推荐返佣，真心比双11还便宜！',
          //   'thumbImage': data.pictUrl,
          //   'webpageUrl': shareUrl
          // }))
          Actions.shareModel()
        }}
        style={{height:50,width:35,justifyContent:'center', paddingRight:10, alignItems:'center'}}>
        <ICON name='md-share' size={25}  color='#000' />
      </TouchableOpacity>
    )
  }

  renderStar(data){
    if(global.isWXAppInstalled){
      return(
        <TouchableOpacity
          onPress={()=>{
            this.props.actions.postUserCollect({...data, resultJifen:1})
          }}
          style={{height:50,width:35,justifyContent:'center', paddingRight:5, alignItems:'center'}}>
          {this.state.like ?
            <ICON name='ios-star' size={25} color='#f00'/>
            : <ICON name='ios-star' size={25} />
          }

        </TouchableOpacity>
      )
    }else{
      return(
        <View></View>
      )
    }
  }


  renderReturnTop(){
    if(this.state.isScroll){
      return(
        <View>
          <TouchableOpacity style={[styles.floatButton, {bottom: 150 ,right:20}]} onPress={()=>{
            this.myScrollView.scrollTo(0, 0)
          }}>
            <Image source={require('./../../../assets/images/top.png')} style={{width:50, height:50}}/>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.floatButton, {bottom: 100 ,right:20}]} onPress={()=>{Actions.jump('dashboard', {refresh:true})}}>
            <Image source={require('./../../../assets/images/ren.png')} style={{width:50, height:50}}/>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.floatButton, {bottom: 50 ,right:20}]} onPress={()=>{Actions.jump('UserHistory', {refresh:true})}}>
            <Image source={require('./../../../assets/images/jiao.png')} style={{width:50, height:50}}/>
          </TouchableOpacity>
        </View>
      )
    }
  }

  render(){

    const {
      isLoading,
      data,
      error
    } = this.props.goodsContent

    if(!data || isLoading){
      return(
        <View style={{flex:1, justifyContent:'center', alignItems:'center', backgroundColor:'#fff'}}>
          <Image source={require('./../../../assets/images/rolling.gif')} style={{width:230, height:230}}/>
        </View>
      )
    }

    if(data && !isLoading){
      return(
        <SafeAreaView style={styles.container}>
          <View style={styles.title}>
            <TouchableOpacity
              onPress={()=>{Actions.pop()}}
              style={{height:50, width:40,justifyContent:'center', paddingLeft:10
              }}>
              <ICON name='ios-arrow-back' size={30}  color='#000'/>
            </TouchableOpacity>
            <Text style={{color:'#000', width:245, fontSize:16}}  numberOfLines={1}>{stringUtils.delHtmlTag(data.title)}</Text>

            {this.renderStar(data)}
            {/*{this.renderShare(data)}*/}

          </View>
          {this.renderContent()}
          {this.renderReturnTop()}
          <Toast2
            ref={view => this.toast = view}
            style={{backgroundColor:'red'}}
            opacity={0.6}
            position='top'/>
        </SafeAreaView>
      )
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#fff'
  },
  title:{
    height: 50,
    justifyContent:'space-between',
    alignItems:'center',
    borderBottomWidth:0.3,
    borderBottomColor:'#999',
    flexDirection:'row',
  },
  webView: {
    flex:1
  },
  imgtop:{
    flex:1,
    height:380,
    resizeMode: "contain"
  },
  titleContainer:{
    padding: 8,
    backgroundColor:'#fff'
  },
  postage:{
    color:'#fff',
    backgroundColor:'#FF5000',
    fontSize:12,

  },
  itemTitle:{
    marginVertical:5,
    letterSpacing:2,
    lineHeight:22,
    marginBottom:30
  },
  floatButton:{
    position:'absolute',
    justifyContent:'center',
    alignItems:'center',
    padding:5,
    borderRadius:30,
    width:35,
    height:35,
    zIndex: 99,
  },
  impressionGood:{
    padding:6,
    borderRadius:50,
    borderWidth:1,
    borderColor:'#FEE',
    backgroundColor:'#FEE',
    justifyContent:'center',
    alignItems:'center',
    marginLeft: 10,
    marginTop: 10
  },
  impressionBad:{
    padding:6,
    borderRadius:50,
    borderWidth:1,
    borderColor:'rgb(204, 204, 204)',
    backgroundColor:'rgb(204, 204, 204)',
    justifyContent:'center',
    alignItems:'center',
    marginLeft: 10,
    marginTop: 10
  }
})

export const LayoutComponent = TaobaoWebScene

export function mapStateToProps(state, props) {
  return {
    routes: state.routes,
    goodsContent: state.goodsContentReducer,
    userLike: state.userLikeReducer,
    postCollect: state.postUserCollectReducer,
    postHistory: state.postUserHistoryReducer,
    userInfo: state.userInfoReducer,
    saveRelation: state.saveRelationReducer,
  }
}